import model
import sqlobject
class search_engine:
    protocols = ['tag:']
    def __init__ (s, q):
        s.protocol = '';
        s.q = q
        s.crack_protocol();

    def crack_protocol(s) :
        for idx, p in enumerate(search_engine.protocols):
            if s.q.find(p) == 0:
                s.protocol = p
                s.q = s.q[len(p):]
                break
        if len(s.protocol) == 0:
            s.protocol = 'keyw:'
    
    def search(s):
        if (s.protocol == 'keyw:'):
            return s.search_keywords()
        elif (s.protocol == 'tag:'):
            return s.search_tag()
        else:
            return 'errrror';
        
    def search_tag(s) :
        ts = list(model.tag.selectBy(name=s.q))
        results = []
        if len(ts) == 0:
            return results
        for b in ts[0].blocks:
            results.append({'note_id':b.note.id, 'title':b.note.title,'block_id':b.id, 'content':b.content});
        return results

    def search_keywords(s):
        keywords = s.q.split(' ')
        results = []
        
        kws=[ model.note.q.title.contains(keyword) for keyword in keywords]
        ns = list(model.note.select(apply(sqlobject.AND, kws)))
        for n in ns:
            results.append({'note_id':n.id, 'title': n.title})
        kws=[model.block.q.content.contains(keyword) for keyword in keywords]
        bs = list(model.block.select(apply(sqlobject.AND, kws)))
        for b in bs:
            results.append({'note_id':b.note.id, 'title':b.note.title, 
                'block_id':b.id, 'content': b.content});
        return results

